package com.gz1;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerSocket_ {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务器 在9999号端口监听 等待连接");
        //当没有客户端连接时会阻塞
        //如果有客户端连接 9999 端口，会返回Socket对象


        //通过serverSocket.getOutputStream()读取写入数据通道的数据
        Socket socket = serverSocket.accept();
        System.out.println("服务器端 serversocket "+socket.getClass());

        InputStream inputStream = socket.getInputStream();
//        byte[] buffer = new byte[1024];
//        int readlen=0;
//        while((readlen=inputStream.read(buffer))!=-1){
//            System.out.println(new String(buffer,0,readlen));
//        }
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
        String str=" ";
        while((str=bufferedReader.readLine())!=null){
            System.out.println(str);
        }
        System.out.println("接受字符成功");


        OutputStream outputStream = socket.getOutputStream();
//        outputStream.write("hello,client".getBytes());
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
        bufferedWriter.write("你好客户端  字符流");
        bufferedWriter.newLine();
        bufferedWriter.flush();
        //每次输出完要用结束标志
//        socket.shutdownOutput();

        //必须关闭
        bufferedWriter.close();
        bufferedReader.close();
        outputStream.close();
        inputStream.close();
        socket.close();
        serverSocket.close();
        System.out.println("服务器端关闭");
    }
}
